package com.springbootdemo.demo.service.impl;

import com.springbootdemo.demo.bean.User;
import com.springbootdemo.demo.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements IUserService {

    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);


    private static final Map<String, User> DATABASES = new HashMap<>();

    static {
        DATABASES.put("1", new User("1", "u1", "p1"));
        DATABASES.put("2", new User("2", "u2", "p2"));
        DATABASES.put("3", new User("3", "u3", "p3"));
    }


    //@Cacheable(value = "user", key = "#id")
    @Override
    public User get(String id) {
        logger.info("进入 get 方法");
        return DATABASES.get(id);
    }


    @CachePut(value = "user", key = "#user.id")
    @Override
    public User saveOrUpdate(User user) {
        DATABASES.put(user.getId(), user);
        logger.info("进入 saveOrUpdate 方法");
        return user;
    }


    @CacheEvict(value = "user", key = "#id")
    @Override
    public void delete(String id) {
        DATABASES.remove(id);
        logger.info("进入 delete 方法");
    }
}
